package
{
	import com.imcrl.component.ext.Sprite;
	
	import flash.geom.Point;
	
	import starling.animation.Tween;
	import starling.display.Image;
	import starling.events.EnterFrameEvent;
	import starling.events.Event;
	import starling.textures.Texture;
	
	import starlingui.component.drag.AbsIcon;
	import starlingui.manager.TextureLoader;
	import starlingui.manager.TextureResource;
	
	public class Background extends Sprite
	{
		private var texture:Texture;
		public function Background()
		{
			super();
		}
		
		
		public function load(url:String):void{
			var loader:TextureLoader=TextureResource.getURL(url);
			if(loader.isReady){
				completeHandle(null,loader);
			}else{
				loader.addEventListener(Event.COMPLETE,completeHandle);
			}
		}
		
		
		protected function completeHandle(event:Event,loader:TextureLoader=null):void{
			if(event){
				loader =event.target as TextureLoader;
				loader.removeEventListener(Event.COMPLETE,completeHandle);
			}
		   
			texture=loader.texture;
			
			update();
			this.addEventListener(EnterFrameEvent.ENTER_FRAME,enterFrameHandle);
		}
		private function enterFrameHandle(event:EnterFrameEvent):void{
			this.x-=1;
			if(x<=-singScrenWidth){
				x+=singScrenWidth;
			}
		}
		
		private var cache:Array=[];
		private function getImage(index:int,col:int):Image{
			var image:Image=cache[index];
			if(image==null){
				image=new Image(texture);
				this.addChild(image);
			}
			image.x=int(index%col*texture.width);
			image.y=int(index/col)*texture.height;
			
			
			return image;
		}
		
		private var w:int;
		private var h:int;
		public function resize(w:int,h:int):void{
			this.w=w;
			this.h=h;
			update();
		}
		
		private var singScrenWidth:int;
		public function update():void{
			if(texture==null)return;
			
			var row:int=Math.ceil(h/texture.height);
			var col:int=Math.ceil(w/texture.width);
			
			singScrenWidth=col*texture.width;
			col<<=1;
			var total:int=row*col;
			
			var image:Image;
			var i:int=0;
			while(i<total){
				getImage(i,col);
				i++;
			}
			
			this.flatten();
		}
		
	}
}